<?php
/**
 * User zgh
 * Email 1803897171@qq.com
 * Date 2021/7/14
 **/

namespace app\admin\service;

use app\admin\item\MenuLoader;
use app\admin\pipeline\ItemAdapter;
use app\admin\validate\MenuValidate;
use app\common\exception\ServiceException;
use app\common\model\MenuModel;
use think\Db;


class MenuService
{

    public static function getMenuData()
    {
        return MenuModel::field('id,pid,title,icon,url as href,target')
            ->where([
                ['is_index', '<>', 1],
                ['status', '=', '1'],
            ])
            ->order([
                'weight' => 'desc',
                'id' => 'asc',
            ])
            ->select()->toArray();
    }

    public static function buildMenuChild($pid, $menuList, $nodeArr)
    {
        $treeList = [];
        foreach ($menuList as &$v) {
            $check = empty($v['href']) ? true : in_array($v['href'], $nodeArr);
            !empty($v['href']) && $v['href'] = url(str_replace(".", '/', $v['href']));
            if ($pid == $v['pid'] && $check) {
                $node = $v;
                $child = self::buildMenuChild($v['id'], $menuList, $nodeArr);
                if (!empty($child)) {
                    $node['child'] = $child;
                }
                if (!empty($v['href']) || !empty($child)) {
                    $treeList[] = $node;
                }
            }
        }
        return $treeList;
    }

    public static function getList($params)
    {
        $dataList = (MenuModel::where([["status", "<>", -1]])->order(["is_index" => "desc", "pid" => "asc", "weight" => "desc"])->select()->toArray());
        $total = count($dataList);
        return ['count' => $total, "dataList" => $dataList];
    }


    public static function del($params)
    {
        $loader = new MenuLoader();
        $id_arr = $loader->addVal(["del_ids" => $params['id']])->addVerify(MenuValidate::class, MenuValidate::SCENE_DEL)->loadItem();
        $id_arr = $id_arr['del_ids'];
        Db::startTrans();
        foreach ($id_arr as $id) {
            $adapter = new ItemAdapter(MenuModel::class);
            $child_model = $adapter->where([["pid", "=", $id], ["status", "<>", -1]])->getModel();
            if ($child_model) {
                Db::rollback();
                throw new ServiceException("存在子级目录不能删除");
            }
            $adapter->whereUpdate([["id", "=", $id]], ["status" => -1]);
        }
        Db::commit();
        return true;
    }

    public static function save($params)
    {
        $loader = new MenuLoader();
        $data = $loader->addVal($params)->loadItem();
        $adapter = new ItemAdapter(MenuModel::class);
        $res = $adapter->save($data);
        if ($res) {
            return $adapter->getId();
        } else {
            return false;
        }
    }


    public static function getByID($id)
    {
        $adapter = new  ItemAdapter(MenuModel::class);
        return $adapter->id($id)->getModel();
    }

    public static function getModule($menu_data = [], &$add_data = [])
    {
        foreach ($menu_data as &$menu_row) {
            if ($menu_row['floor_num'] > 0) {
                $menu_row['show'] = str_repeat(str_repeat("&nbsp;", 6), $menu_row['floor_num']) . str_repeat("├", $menu_row['floor_num']) . str_repeat("&nbsp;", 6) . $menu_row['title'];
            } else {
                $menu_row['show'] = $menu_row['title'];
            }
            $add_data[] = $menu_row;
            self::getModule($menu_row['child'], $add_data);
        }
    }


    public static function getMenuAll($pid = 0, $floor_num = 0)
    {
        $menu = MenuModel::field("id,title")->where([["is_index", "<>", 1], ["pid", "=", $pid], ['status', "<>", -1]])->order(["weight" => "desc", "id" => "asc"])->select();
        foreach ($menu as &$menu_row) {
            $menu_row['floor_num'] = $floor_num;
            $menu_row['child'] = self::getMenuAll($menu_row['id'], $floor_num + 1);
        }
        return $menu;
    }


}
